package com.siblings.loan.ui.tab.act

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.View
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.lib.base.base.BaseFragment
import com.lib.base.utils.helper.ForegroundBackgroundHelper
import com.lib.base.utils.helper.ForegroundBackgroundObserver
import com.lib.base.utils.log.LogHelper
import com.siblings.lib_baseadapter.SIBOnItemChildClickListener
import com.siblings.loan.R
import com.siblings.loan.databinding.ActMainBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.loan.fm.SibLoanOrderFm
import com.siblings.loan.ui.tab.adapter.SibTabAdapter
import com.siblings.loan.ui.tab.impl.SibMainPresenterImpl
import com.siblings.loan.ui.tab.view.ISibMainView
import com.siblings.loan.ui.user.fm.SibUserMenuFm
import com.siblings.loan.utils.event.SibEventData
import com.siblings.loan.utils.event.SibEventType
import com.siblings.mvp.MvpAct
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/8 16:42
 * @Annotation：主页
 */

class SibMainAct : MvpAct<ISibMainView,SibMainPresenterImpl>(),ISibMainView {
    lateinit var binding: ActMainBinding

    private var tabAdapter: SibTabAdapter? = null

    private var fragmentManager: FragmentManager? = null
    private var curtFragment = Fragment()
    override fun getSibRootView(): View {
        binding = ActMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createMvpPresenter(): SibMainPresenterImpl {
        return SibMainPresenterImpl(this)
    }

    override fun initSibView() {
        setBackExit(true)
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        addSibMenuFragment()
        initSibRecyclerView()

        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initSibListener() {

    }

    override fun initSibData() {
        mvpPresenter.loadSibTabList()
        mvpPresenter.loadSibFragmentList()
    }

    /**
     * 初始化Tab列表
     */
    private fun initSibRecyclerView() {
        binding.tabBar.layoutManager = GridLayoutManager(getContext(), 3)
        tabAdapter = SibTabAdapter(binding.tabBar)
        binding.tabBar.adapter = tabAdapter
        binding.tabBar.itemAnimator = DefaultItemAnimator()
        tabAdapter!!.setOnItemChildClickListener(SIBOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item
                mvpPresenter.setSibCurrentItemIndex(position)
            }
        })
    }


    /**
     * 设置tabList
     */
    override fun showSibTabList(tabList: ArrayList<JSONObject>) {
        tabAdapter!!.data = tabList
    }

    /**
     * 刷新Tab
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun notifyTabDataChanged() {
        tabAdapter!!.notifyDataSetChanged()
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    override fun showSibFragment(fragment: BaseFragment, index: Int) {
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        val transaction = fragmentManager!!.beginTransaction()
        //如果之前没有添加过
        if (!fragment.isAdded) {
            //第三个参数为添加当前的fragment时绑定一个tag
            transaction.hide(curtFragment).add(R.id.contentLayout, fragment, "$index")
        } else {
            transaction.hide(curtFragment).show(fragment)
            when(index){
                0 -> {//首页
                }
                1 -> {//订单
                    val orderFm = fragment as SibLoanOrderFm
                    orderFm.onSibRefreshOrderList()
                }
                else -> {//数据安全
                }
            }
        }
        curtFragment = fragment
        transaction.commitAllowingStateLoss()
    }

    /**
     * 展示个人中心
     */
    fun showSibMenuFragment(eventRemark: String){
        val isOpen = binding.drawerLayout.isDrawerOpen(GravityCompat.START)
        if (isOpen){//是否打开
            binding.drawerLayout.closeDrawer(GravityCompat.START,true)
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER,eventRemark)
        } else {
            binding.drawerLayout.openDrawer(GravityCompat.START,true)
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER,eventRemark)
        }
    }

    /**
     * 添加侧边菜单
     */
    private fun addSibMenuFragment(){
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        fragmentManager!!
            .beginTransaction()
            .add(R.id.menuLayout, SibUserMenuFm(binding.drawerLayout)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            LogHelper.e("sib loan main background>>>>>>>>>$isForeground")
            //从桌面进入前台，需要刷新总流程
            if (isForeground) {
                EventBus.getDefault().post(SibEventData(SibEventData.TYPE.SIB_PROCESS_REFRESH))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}